const Controller = require('egg').Controller;

class AdminController extends Controller {
  async index() {
    this.ctx.body = await this.ctx.service.user.memory();
  }
  async login() {
    let { ctx } = this;
    let uname = ctx.request.body.uname;
    let upwd = ctx.request.body.upwd;
    let obj = {};
    if (!uname) {
      obj = { code: 301, msg: '用户名不可以为空' };
      return;
    }
    if (!upwd) {
      obj = {
        code: 302,
        msg: '密码不能为空'
      };
    }
    let res = await ctx.service.admin.login(ctx.request.body);
    if (res.length > 0) {
      let time = 3600;
      let token = await ctx.service.admin.getToken({
        _id: res[0].uid
      }, time);

      //存储到cookie
      ctx.cookies.set('token', token, {
        maxAge: time * 1000,
        path: '/',
        domain: '127.0.0.1',
        httpOnly: false
      });
      obj = {
        code: 200,
        msg: '登录成功',
        token
      };
    } else {
      obj = {
        code: 301,
        msg: '登录失败，不存在该用户'
      };
    }
    ctx.body = obj;
  }

  //小程序的登录接口
  async mpLogin() {
    let { ctx } = this;
    //调用后端
    //https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
    let mpConfig = {
      appid: 'wx6c8fd09d227a3de0',
      secret: '656bf2a420d132106c3adf48a4b9250d',
      js_code: ctx.query.code,
      grant_type: 'authorization_code'
    };
    let url = '//api.weixin.qq.com/sns/jscode2session';
    const res = await ctx.curl(url, {
      method: 'GET',
      data: mpConfig,
      dataType: 'json'
    });
    this.ctx.body = res;
  }
}

module.exports = AdminController;
